package net.jueb.protobufs2.server;
import net.jueb.protobufs2.pojo.MessageProto.Message;
import net.jueb.protobufs2.pojo.MessageProto.MessageType;
import net.jueb.protobufs2.pojo.MessageProto.Response;
import net.jueb.protobufs2.pojo.MessageProto.Result;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

public class ProtobufServerHandler extends ChannelHandlerAdapter{

	
	private Message getResult(int msgId,int resultCode,String resultinfo)
	{
		Response.Builder rspBuilder=Response.newBuilder();//响应类消息
		//构建result实体类
		Result result=Result.newBuilder().setCode(resultCode).setInfo(resultinfo).build();
		Message.Builder msgBuilder=Message.newBuilder();//消息主体
		msgBuilder.setMsgId(msgId);//消息主体ID
		msgBuilder.setMsgType(MessageType.Type_Result);//携带消息类型
		msgBuilder.setResponse(rspBuilder.setResult(result));//由内到外设置实体属性
		return msgBuilder.build();
	}
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		while(true)
		{
			ctx.writeAndFlush(getResult(Thread.currentThread().hashCode(),2, "LoginOk"));
		}
	}
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)throws Exception {
		Message m=(Message)msg;
		if(m==null)
		{
			return;
		}
		switch (m.getMsgType().getNumber()) {
		case MessageType.Type_Regist_VALUE:
			System.out.println("收到注册请求:"+m.getRequest().getRegist());
			ctx.writeAndFlush(getResult(Thread.currentThread().hashCode(),1, "RegistOk"));
			break;
		case MessageType.Type_Login_VALUE:
			System.out.println("收到登录请求:"+m.getRequest().getLogin());
			ctx.writeAndFlush(getResult(Thread.currentThread().hashCode(),2, "LoginOk"));
			break;
		default:
			System.out.println("收到请求:"+m);
			break;
		}
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		cause.printStackTrace();
		ctx.close();
	}
}
